﻿//
// eCRAM, a monthly activity report web application
// Copyright (C) 2010  Aptea
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//

using System;
using System.Web.Mvc;
using System.Web.Routing;

using Microsoft.Practices.Unity;

namespace eCram.IoC
{
    /// <summary>
    /// Registers the controllers via the Unity framework.
    /// </summary>
    /// <remarks>
    /// Change the default controller factory so that each time the creation
    /// of a new controller is needed, we use Unity (IoC) to create the
    /// controller.
    /// </remarks>
    public class UnityControllerFactory : DefaultControllerFactory
    {
        /// <summary>
        /// Unity framework.
        /// </summary>
        private readonly IUnityContainer _container;

        /// <summary>
        /// Creates the factory that will create the controllers.
        /// </summary>
        /// <param name="container">Unity framework</param>
        public UnityControllerFactory(IUnityContainer container)
        {
            _container = container;
        }

        /// <summary>
        /// Creates a controller using Unity (IoC) instead of the default behaviour.
        /// </summary>
        protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
        {
            try
            {
                if (controllerType == null)
                    throw new ArgumentNullException("controllerType");

                if (!typeof(IController).IsAssignableFrom(controllerType))
                    throw new ArgumentException(string.Format(
                        "Type requested is not a controller: {0}",
                        controllerType.Name),
                        "controllerType");

                return _container.Resolve(controllerType) as IController;
            }
            catch { return null; }
        }
    }
}
